package my.com.sunway.util;

import org.apache.log4j.*;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;

public class HibernateUtil {
    static Logger log = Logger.getLogger(HibernateUtil.class);

    protected static final SessionFactory sessionFactory;
    static {
        try {
            //     Create the SessionFactory
            sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
        } catch (Throwable ex) {
            //     Make sure you log the exception, as it might be swallowed
            log.error("Initial SessionFactory creation failed.", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static final ThreadLocal session = new ThreadLocal();

    public static Session currentSession() {
        Session s = null;
        
        try{
        s = (Session) session.get();
          //     Open a new Session, if this Thread has none yet
          if (s == null) {
              s = sessionFactory.openSession();
              session.set(s);
          }
        }catch(Exception ex){
          log.error(ex.toString());
        }finally{
          return s;
        }
    }

    public static void closeSession() {
      try{
        Session s = (Session) session.get();
        if (s != null)
            s.close();
        session.set(null);
        }catch(Exception ex){
          log.error(ex.toString());
        }
    }
}
